import router from './router'
import store from './store'

// 白名单
const whiteList = ['/login']

/**
 * 路由前置守卫
 * @param {*}  to 要到哪里去
 * @param {*}  from 你从哪里来
 * @param {*}  next 是否要去?
 */

router.beforeEach(async (to, from, next) => {
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      //判断用户资料是否获取
      //若不存在用户信息，则需要获取用户信息
      if (!store.getters.hasUserInfo) {
        // 触发获取用户信息的action
        const { permission } = await store.dispatch('user/getUserInfo')
        permission.menus = [
          'screen',
          'three_view',
          'run_monitor',
          'run_product',
          'run_video',
          'run_warning',
          'equip_manage',
          'asset_overview',
          'asset_equipment',
          'out_record',
          'in_record',
          'ops_manage',
          'on_duty',
          'scheduling',
          'duty_record',
          'personnel_record',
          'see_also',
          'patrol_point',
          'patrol_scheme',
          'patrol_record',
          'upkeep',
          'acpp',
          'service',
          'question',
          'access_corridor',
          'line_apply',
          'line_manage',
          'work_order',
          'working',
          'energy_consumption',
          'work_ticket',
          'data_manage',
          'rescue_team',
          'hospital',
          'plan',
          'knowledge',
          'sys_manage',
          'org_manage',
          'role_manage',
          'user_manage',
          'permission_manage'
        ]
        // 处理用户权限，筛选出需要添加的权限
        const filterRoutes = await store.dispatch(
          'permission/filterRoutes',
          permission.menus
        )
        // 利用 addRoute 循环添加
        filterRoutes.forEach((item) => {
          router.addRoute(item)
        })
        // 添加完动态路由之后，需要在进行一次主动跳转
        // return next(to.path)
        next({ ...to, replace: true })
      } else {
        if (to.path === '/404' && to.redirectedFrom?.fullPath === '/') {
          next({ path: to.redirectedFrom?.fullPath, replace: true })
        } else {
          next()
        }
      }
    }
  } else {
    // 2.用户未登录，只允许进入白名单
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
})
